<script lang="ts" setup>
import { phoneSplit } from "@/utils";
import debounce from "@/utils/debounce";
import { login, wxlogin } from "@/api/login";
import { interpreter } from "@/api/request";
import {
  computed,
  ref,
  onBeforeUnmount,
  onMounted,
  getCurrentInstance
} from "vue";
import toLoginPage from "@/utils/toLoginPage";
import sendCode, { send } from "@/utils/sendCode";
import { useUserInfo } from "@/store/user";
import Lnkyeah from "@/utils/lnkyeah";
// #ifdef H5
import Speech from "@/utils/speech";
// #endif

const instance: any = getCurrentInstance();
const codeMessages = ref<string>("");
const secondCount = ref<string>("");
const focus = ref<boolean>(true);
const { handleUpdateInfo } = useUserInfo();

const props = defineProps<{ phone?: string }>();
let timer = 0;

onMounted(() => {
  if (!props.phone) {
    uni.redirectTo({
      url: "/pages/login/login"
    });
  }
  handleTimeDown();
});
onBeforeUnmount(() => {
  clearInterval(timer);
});

const getCode = computed(() => {
  return Array.from({
    length: 4
  }).map((_, index) => codeMessages.value[index]);
});

const getIndex = computed(() => {
  return getCode.value.filter(item => item).length;
});

const btnDisabled = computed(() => {
  return secondCount.value !== "";
});
const handleSendCode = debounce(async () => {
  //  #ifdef H5
  const isOk = await sendCode(props.phone as string);
  if (secondCount.value === "" && isOk) {
    uni.showToast({
      title: "发送成功~",
      icon: "success",
      mask: true
    });
    handleTimeDown();
  }
  // #endif
  // #ifdef MP-WEIXIN
  instance.ctx.selectComponent("#captcha").show();
  // #endif
}, 300);

const handleTimeDown = () => {
  let countDown = 60;

  timer = setInterval(() => {
    countDown--;
    secondCount.value = `${countDown}s后`;

    // 当倒计时为0时清除计时器
    if (countDown === 0) {
      secondCount.value = "";
      clearInterval(timer);
    }
  }, 1000);
};

const handleInputChange = (bool: boolean) => {
  console.log(bool);
  focus.value = bool;
};

const handleInput = async (e: any) => {
  const value = e.detail.value;
  if (value.length >= 4 && props.phone) {
    // #ifdef MP-WEIXIN
    const getMiniCode = () => {
      return new Promise(resolve => {
        uni.login({
          provider: "weixin",
          success: async res => {
            console.log("res", res);
            resolve(res.code);
          }
        });
      });
    };
    const code = await getMiniCode();
    const [err, res] = await interpreter(
      login(
        props.phone,
        value,
        getApp().globalData!.share_user_uuid,
        code as string
      )
    );
    // #endif
    // #ifdef H5
    const [err, res] = await interpreter(
      login(props.phone, value, getApp().globalData!.share_user_uuid)
    );
    // #endif
    if (!err) {
      toLoginPage.reset();
      Lnkyeah.instance.closeSocket();
      Lnkyeah.instance.login();
      // #ifdef H5
      Speech.instance.init();
      // #endif
      handleUpdateInfo(res);

      uni.switchTab({
        url: "/pages/shop/index/shop_index"
      });
    } else {
      uni.showToast({
        icon: "none",
        title: "验证码错误"
      });
    }
  }
};

const handlerVerify = async (res: any) => {
  if (props.phone) {
    const isok = await send(props.phone, res);
    if (isok) {
      handleTimeDown();
      uni.showToast({
        icon: "none",
        title: "发送成功"
      });
    } else {
      uni.showToast({
        icon: "none",
        title: "发送失败"
      });
    }
  }
};
const handlerError = () => {
  uni.showToast({
    icon: "none",
    title: "发送失败"
  });
};
</script>

<template>
  <!-- #ifdef MP-WEIXIN -->
  <t-captcha
    id="captcha"
    app-id="190901371"
    @verify="handlerVerify"
    @error="handlerError"
  />
  <!-- #endif -->
  <Container>
    <view class="login">
      <view class="font-48"> 输入验证码 </view>
      <view class="code-text">
        <view class="text1">
          我们发送了一个{{ getCode.length }}位数的验证码给：
        </view>
        <view class="text2">
          {{ props.phone ? phoneSplit(props.phone) : "" }}
        </view>
      </view>
      <input
        :focus="getIndex + 1 ? focus : false"
        class="hide-input"
        ref="input"
        type="number"
        maxlength="4"
        v-model="codeMessages"
        @blur="focus = false"
        @input="e => handleInput(e)"
      />

      <Flex justify="space-between">
        <view
          v-for="(item, index) in getCode"
          :key="index"
          :class="['code-item', getIndex === index ? 'code-item-active' : '']"
          @click="handleInputChange(true)"
        >
          {{ item }}
        </view>
      </Flex>

      <t-button
        :type="secondCount ? '' : 'deep'"
        :backgroundColor="
          btnDisabled ? 'var(--btn-bg-color-disabled)' : '#333333'
        "
        :disabled="btnDisabled"
        labelColor="#fff"
        margin="24px auto 0"
        width="670rpx"
        height="80rpx"
        borderRadius="20rpx"
        @click="handleSendCode"
      >
        {{ secondCount }}重新发送
      </t-button>
    </view>
  </Container>
</template>

<style lang="scss" scoped>
@keyframes blinkAnimation {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
.code-item {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: #f9f9f9;
  font-size: 24px;
  color: #111;
  font-weight: bold;
  margin: 0 10px;
  box-sizing: border-box;
  line-height: 60px;
  &-active {
    position: relative;
    border: 1px solid var(--color-primary-info);

    &::after {
      content: "";
      position: absolute;
      top: 50%;
      left: 11px;
      width: 2.5px;
      height: 50%;
      background: var(--color-primary-info);
      transform: translate(-50%, -50%);
      border-radius: 10px;
      /* 1s表示动画周期，infinite表示无限循环 */
      animation: blinkAnimation 1.5s infinite;
    }
  }
}
.login {
  padding: 0 40rpx;
  margin: 94px auto 0;
  text-align: center;
  .hide-input {
    position: fixed;
    top: -100vh;
    opacity: 0;
  }

  .code-text {
    padding: 20px 0 15px;
    font-size: 14px;

    .text1 {
      color: #666;
    }

    .text2 {
      color: var(--color-text-assist-1);
      font-weight: bold;
      padding-top: 5px;
    }
  }
}

.font-48 {
  font-size: 24px;
  font-weight: 500;
  color: var(--color-text-default);
}
</style>
